<template>
  <div class="messages-page">
    <div class="page-header">
      <h1>Contact Messages</h1>
      <el-select v-model="filter.status" placeholder="All Status" clearable @change="loadMessages">
        <el-option label="Unread" :value="0" />
        <el-option label="Read" :value="1" />
      </el-select>
    </div>

    <!-- Messages Table -->
    <el-card>
      <el-table v-loading="loading" :data="messages" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Name" width="150" />
        <el-table-column prop="country" label="Country" width="120" />
        <el-table-column prop="email" label="Email" width="200" />
        <el-table-column prop="phone" label="Phone" width="150" />
        <el-table-column prop="message" label="Message" min-width="250" show-overflow-tooltip />
        <el-table-column label="Status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'warning'" size="small">
              {{ row.status ? 'Read' : 'Unread' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="Date" width="180" />
        <el-table-column label="Actions" width="220" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewMessage(row)">View</el-button>
            <el-button
              v-if="!row.status"
              size="small"
              type="success"
              @click="markAsRead(row.id)"
            >
              Mark as Read
            </el-button>
            <el-popconfirm
              title="Are you sure to delete this message?"
              @confirm="deleteMessage(row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger">Delete</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          :page-size="pagination.limit"
          :total="pagination.total"
          layout="total, prev, pager, next"
          @current-change="loadMessages"
        />
      </div>
    </el-card>

    <!-- Message Detail Dialog -->
    <el-dialog
      v-model="detailDialogVisible"
      title="Message Details"
      width="600px"
    >
      <div v-if="selectedMessage" class="message-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="Name">{{ selectedMessage.name }}</el-descriptions-item>
          <el-descriptions-item label="Country">{{ selectedMessage.country || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Email">{{ selectedMessage.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Phone">{{ selectedMessage.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Date">{{ selectedMessage.created_at }}</el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag :type="selectedMessage.status ? 'success' : 'warning'" size="small">
              {{ selectedMessage.status ? 'Read' : 'Unread' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="message-content">
          <h4>Message:</h4>
          <p>{{ selectedMessage.message }}</p>
        </div>

        <div class="contact-actions">
          <h4>Quick Contact:</h4>
          <el-button
            v-if="selectedMessage.email"
            type="primary"
            @click="openEmail(selectedMessage.email)"
          >
            Reply via Email
          </el-button>
          <el-button
            v-if="selectedMessage.phone"
            type="success"
            @click="openWhatsApp(selectedMessage.phone)"
          >
            Contact via WhatsApp
          </el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">Close</el-button>
        <el-button
          v-if="selectedMessage && !selectedMessage.status"
          type="success"
          @click="markAsReadAndClose(selectedMessage.id)"
        >
          Mark as Read
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { contactAPI } from '@/api'

const loading = ref(false)
const messages = ref([])
const detailDialogVisible = ref(false)
const selectedMessage = ref(null)

const filter = reactive({
  status: null
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const loadMessages = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      limit: pagination.limit
    }

    if (filter.status !== null) {
      params.status = filter.status
    }

    const response = await contactAPI.getAll(params)
    if (response.success) {
      messages.value = response.data
      Object.assign(pagination, response.pagination)
    }
  } catch (error) {
    console.error('Failed to load messages:', error)
  } finally {
    loading.value = false
  }
}

const viewMessage = (message) => {
  selectedMessage.value = message
  detailDialogVisible.value = true
}

const markAsRead = async (id) => {
  try {
    await contactAPI.updateStatus(id, 1)
    ElMessage.success('Message marked as read')
    loadMessages()
  } catch (error) {
    console.error('Failed to update message status:', error)
  }
}

const markAsReadAndClose = async (id) => {
  await markAsRead(id)
  detailDialogVisible.value = false
}

const deleteMessage = async (id) => {
  try {
    await contactAPI.delete(id)
    ElMessage.success('Message deleted successfully')
    loadMessages()
  } catch (error) {
    console.error('Failed to delete message:', error)
  }
}

const openEmail = (email) => {
  window.location.href = `mailto:${email}`
}

const openWhatsApp = (phone) => {
  const cleanPhone = phone.replace(/\s/g, '')
  window.open(`https://wa.me/${cleanPhone}`, '_blank')
}

onMounted(() => {
  loadMessages()
})
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;

  h1 {
    margin: 0;
    color: var(--text-primary);
  }
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}

.message-detail {
  .message-content {
    margin: 2rem 0;

    h4 {
      margin-bottom: 0.5rem;
      color: var(--text-primary);
    }

    p {
      line-height: 1.8;
      color: var(--text-secondary);
      white-space: pre-wrap;
      padding: 1rem;
      background-color: #f5f5f5;
      border-radius: 8px;
    }
  }

  .contact-actions {
    h4 {
      margin-bottom: 1rem;
      color: var(--text-primary);
    }

    .el-button {
      margin-right: 1rem;
    }
  }
}
</style>

